/*
 * @Author: caiqi
 * @Date: 2019-02-14 14:34:34
 * @Last Modified by: cai.qi
 * @Last Modified time: 2020-05-11 09:59:04
 * @Describe:
 */

"use strict";

import { Service } from "egg";

export default class TypeService extends Service {
    // ------------------------------ 获取所有品类
    async get(body: any) {
        const { ctx } = this;
        // const _body = body;
        console.log(body)
        const data = await ctx.model.ModType.findAll({
            where: { status: 1 },
            // ASC:升序(默认),DESC:降序。
            order: [['sort', 'DESC'], [['created_at', 'DESC']]],
        });
        return data;
    }
    async create(body: any) {
        const { ctx } = this;
        const type = await ctx.model.ModType.findOne({ where: { name: body.name, status: 1 } });
        if (type) {
            return ctx.throw('该品类已存在', 201);
        }
        const data = await ctx.model.ModType.create(body);
        return data;
    }
    async updata(id: any, body: any) {
        const { ctx } = this;
        const type = await ctx.model.ModType.findOne({ where: { id } });

        if (type) {
            const data = await type.update(body);
            return data;
        } else {
            return ctx.throw('无此ID', 201);
        }
    }
    async del(id: any) {
        const { ctx } = this;
        const type = await ctx.model.ModType.findOne({ where: { id } });

        if (type) {
            await type.update({ ...type, status: 0 });
            return {};
        } else {
            return ctx.throw('无此ID', 201);
        }
    }
}
